// pages/edit/edit.js
const util = require('../../utils/util.js');

const app = getApp()

import {
  addNote,
  updateNote
} from './../../api/nots.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: null, //标题
    content: null, //内容
    time: null, //时间
    _id: 0, //id
    action: 0, //0 添加 1 修改
    index: 0 //action=1时生效
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    // 0 添加  1 修改
    if (options.action == 1) {
      let item = JSON.parse(options.item)
      //当前item的数组中的下标
      this.data.index = options.index
      this.data.item = item
      this.setData({
        title: item.title,
        content: item.content,
        time: item.time,
        action: options.action,
        _id: item._id,
      })

    } else {
      let date = new Date()
      this.setData({
        time: util.formatTime(date)
      })
    }

  },
  /**
   * 点击保存按钮
   */
  onClickSumbit: function () {

    if (!this.checkInputEmpty()) {
      //保存或修改数据
      this.updateNetworkInfo()

    }
  },

  /**
   * 更新网络数据
   */
  updateNetworkInfo() {
    let info = this.data.item || {}
    //内容标题
    info.title = this.data.title
    info.content = this.data.content
    info.time = this.data.time
    if (this.data.action == 1) {
      wx.showLoading({
        title: '更新中...',
      })
      info.index = this.data.index
      info.updateTime = Date.now();
      updateNote(info).then(res => {
        console.log("updateNote", res)
        wx.hideLoading()
        info._id = this.data._id
        info.index = this.data.index
        this.onBackPress(info)
      }).catch(res => {
        wx.hideLoading()
        console.log('error', res)
      })
    } else {
      wx.showLoading({
        title: '保存中...',
      })
      addNote(info, true).then(res => {
        console.log("addNote success", res)
        wx.hideLoading()
        if (res.local) {
          //没网保存在本地
          console.log("本地缓存")
        } else {
          //将数据库对应id赋值给info
          // if (res.result && res.result._id) {
          //   info._id = res.result._id
          // } else {
          //   info = null
          // }
          info._id = res._id
        }
        this.onBackPress(info)
      }).catch(res => {
        console.log("")
      })
    }
  },
  onBackPress(info) {
    util.navigateBackResult({
      data: {
        editResult: info
      }
    })
  },
  /**
   * 检测输入框是否为空
   */
  checkInputEmpty() {
    let result = false;
    if (!this.data.title || "" == this.data.title) {
      wx.showToast({
        title: '请输入标题',
        icon: "error"
      })
      result = true;
    } else if (!this.data.content || "" == this.data.content) {
      wx.showToast({
        title: '请输入内容',
        icon: "error"
      })
      result = true;
    }
    return result
  },
  onTitleInput: function (params) {
    this.data.title = params.detail.value
  },
  onContentInput: function (params) {
    this.data.content = params.detail.value
  },
})